package com.bieber.smartpost;

import com.bieber.smartpost.util.Utils;

import java.util.Arrays;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by bieber on 14-10-25.
 */
public class Pool {



    private static final ReentrantLock LOCK = new ReentrantLock();

    private static final Condition NOT_FULL = LOCK.newCondition();

    private static final Condition NOT_EMPTY = LOCK.newCondition();

    private int maxSize=10;

    private int currentSize=0;

    private Object[] array = new Object[maxSize];


    public void offer(Object item) throws InterruptedException {
        try {
            LOCK.lockInterruptibly();
        } catch (InterruptedException e) {
            Utils.COMMONS_LOGGER.debug("lock exception ",e);
        }
        try{
            if(maxSize==currentSize){
                NOT_FULL.await();
            }
            array[currentSize]=item;
            currentSize++;
            NOT_EMPTY.signal();
        }finally {
            LOCK.unlock();
        }
    }


    public Object pop() throws InterruptedException {
        try {
            LOCK.lockInterruptibly();
        } catch (InterruptedException e) {
            Utils.COMMONS_LOGGER.debug("lock exception ", e);
        }
        try{
            if(currentSize==0){
                NOT_EMPTY.await();
            }
            currentSize--;
            Object item = array[currentSize];
            array[currentSize]=null;
            NOT_FULL.signal();
            return item;
        }finally {
            LOCK.unlock();
        }
    }

    @Override
    public String toString() {
        return "Pool{" +
                "maxSize=" + maxSize +
                ", currentSize=" + currentSize +
                ", array=" + Arrays.toString(array) +
                '}';
    }
}
